<template>
    <div class="login">
        <h3>OMSS运维辅助管理系统</h3>
        
        <el-form
            ref="ruleFormRef"
            :model="ruleForm"
            status-icon
            :rules="rules"
            class="demo-ruleForm"
        >   
            <!-- prop 就是下面定义的prop -->
            <el-form-item  prop="username">
                <!--    大小                                    插槽       -->
                <el-input size="large" placeholder="请输入用户名" v-model="ruleForm.username" >
                    <!-- 图标使用 -->
                     <template #prefix>
                        <el-icon :size="25"><UserFilled /></el-icon>
                    </template>
                </el-input > 
            </el-form-item>
            <el-form-item  prop="password">
                <el-input
                    size="large"
                    placeholder="请输入密码"
                    v-model="ruleForm.password"
                    :type="pwdType"
                    autocomplete="off"
                    class="pwd-input"
                >
                    <template #prefix>
                        <el-icon :size="25"><Lock /></el-icon>
                    </template>
                    <template #suffix>
                      <span class="show-pwd" @click="chanPwdType">
                        <svg-icon :name="pwdType === 'password' ? 'eye-open' : 'eye-close'" />
                      </span>
                    </template>
                </el-input>

              
            </el-form-item>
            <el-form-item>
              <!-- 传递form组件ruleFormRef  防抖自定义指令：v-debounce="'handleClick'" -->
            <el-button class ="login-btn" 
            type="primary" 
            @click="submitForm(ruleFormRef)"
            v-debounce="'handleClick'"
            >登录</el-button>
            <el-button class ="reset-btn" @click="resetForm(ruleFormRef)">重置</el-button>
            </el-form-item>
        </el-form>
    </div>
    <div class="login-copyright">
      <div class="mb5 login-copyright-company">{{ ("当前的备案号：") }}</div>
    <div class="login-copyright-msg">{{ ("当前版本：V1.0.0") }}</div>

    </div>
</template>

<script setup lang="ts"> 
// import { loginApi } from './api' 
// loginApi();
import { reactive, ref } from 'vue';
import type { FormInstance, FormRules } from 'element-plus';
import { Lock, UserFilled , Mouse  } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';  //引入 消息提示组件  在main.ts中导入样式import 'element-plus/dist/index.css'
import { loginApi } from './api';
import { useRouter } from 'vue-router';
import SvgIcon from '@/components/SvgIcon/index.vue'
import { useUserStore } from '@/store/user';

const router  = useRouter();
const userStore = useUserStore()

//存储token的key
const ruleFormRef = ref<FormInstance>()    //获取form组件实例  因为是ts 所以指定泛型

//校验逻辑
const validateUser = ( rule: any, value: any, callback: any) => {
  if (value === '' || value === 'null') {
    //如果校验不通过，必须调用 callback 并传入 Error 对象
    callback(new Error('用户信息不能为空'))
  } else {
    if (ruleForm.password !== '') {
      if (!ruleFormRef.value) return
      ruleFormRef.value.validateField('password', () => {})
    }
    callback();
  }
}
const validatePass2 = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('密码不能为空'))
  } else if (value.length < 3) {  // 两次输入不一致
    callback(new Error("密码长度不能少于6位"))
  } else {
    callback()
  }
}

//表单数据
const ruleForm = reactive({
  username: '',
  password: '',
})

//表单校验 自定义规则
const rules = reactive<FormRules<typeof ruleForm>>({
  username: [{ validator: validateUser, message:"用户信息不能为空", trigger: 'blur' }],
  password: [{ validator: validatePass2, message:"用户密码不能为空", trigger: 'blur' }],
})

//拿到 上面定义的 ruleFormRef 实例  FormInstance
const submitForm = (formEl: FormInstance| undefined) => {
  if (!formEl) return
  formEl.validate(async(valid) => {   //valid 是一个boolean值
    // const res = await loginApi(ruleForm)
    // const token = res.data.token
    // console.log("这里是请求的token",token)
    //只在当前页面有效
    // sessionStorage.setItem('token', res.data.access)
    // sessionStorage.setItem('refreshToken', res.data.refresh)
    if (valid) {
      //如果校验通过 ，发起登录请求 这里掉：G:\giteeOmss\omss\omss\src\views\api\index.ts
      loginApi(ruleForm).then((response) => {
          //console.log("这里是登录的res：",response.data.code)
          const token = response.data.data.token
          // const refreshToken = response.data.data.refreshToken
          /// 这一块有问题  视频中是有code等  但是新的只有 access  refacces
          if(response.data.code === 200 ){
            // 1 存储token到本地存储  永久存储
            //localStorage.setItem('refreshToken', refreshToken);
            localStorage.setItem('token', response.data.data.tokenHeader + token);
            // // 更新用户状态
            userStore.setUserInfo({ token })
            ElMessage.success('登录成功！');
            // 2 登录成功后跳转到首页  因为是动态路由  所以这里跳转首页  需要使用router.push
            router.push('/index');
          }
      });

    } else {
      console.log('error submit!',valid)
      //return false    // 不需要显式 return false，因为 validate 回调应无返回值
      //想要弹窗提示用户名或者密码错误: 弹窗上面已经导入了
      ElMessage.error('用户名或者密码错误！');
    }
  }).catch((err) => {
    console.log(err)
    ElMessage.error('用户名或者密码错误！');
  })
}


const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}

//定义密码框显示隐藏
const  pwdType = ref('password');
const chanPwdType = ()=>{
  //如果ref定义的响应式数据  在script中使用 需要加.value
  if(pwdType.value==='password'){
    pwdType.value='text'
  }else{
    pwdType.value='password'
  }
}

//打印所有路由
// console.log(router.getRoutes())

</script>

<!-- yarn add less  -D -->
<style scoped lang="less">
.login{
    // background-color: darkcyan;
    width: 400px;
    margin: 0 auto;
    margin-top: 200px;
    padding: 20px;
    box-shadow: 0 0 10px #ccc;
    :deep(.el-input__inner){
        height: 50px;
    }
}
.show-pwd {
  font-size: 13px;
  cursor: pointer;
  user-select: none;
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  line-height: 1; /* 添加这行，消除行高影响 */
  padding: 0 10px;
}

.login-btn{
    width: 40%;
    margin-top: 20px;
}

.reset-btn{
    width: 40%;
    margin-top: 20px;
    margin-left: 10px;
    // 靠右
    margin-left: 60px
}

.login-copyright {
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
  bottom: 30px;
  text-align: center;
  color: var(--color-whites);
  font-size: 12px;
  opacity: 0.8;
  .login-copyright-company {
    white-space: nowrap;
  }
  
}
/** 备案号 */
// .login-copyright {
//   position: absolute;
//   bottom: 10px;
//   left: auto;
//   font-size: 12px;
//   font-weight: bold;
// }
</style>